package myblc

import (
	"time"
	"crypto/sha256"
	"bytes"
	"strconv"
	"fmt"
)

type Block struct {
	PrevBlockHash []byte
	Hash []byte
	Data []byte
	Timestamp int64
	Height int64
}



func (block *Block) SetHash() {
	//将整数转换成 []byte
	heightBytes := IntToHex(block.Height)

	//将时间戳转换成 []byte
	timeString := strconv.FormatInt(block.Timestamp, 2)
	timeBytes := []byte(timeString)

	//拼接所有属性
	blockBytes := bytes.Join([][]byte{
		block.PrevBlockHash,block.Data,timeBytes, heightBytes},[]byte{})

	//生成Hash
	hash := sha256.Sum256(blockBytes)
	block.Hash = hash[:]
}

//1、创建新区块
func NewBlock(data string, height int64, prevBlockHash []byte) *Block {

	// 创建区块
	block := &Block{PrevBlockHash:prevBlockHash, Hash:nil, Data:[]byte(data), Timestamp:time.Now().Unix(), Height:height}

	//设置Hash值
	block.SetHash()

	fmt.Println(block.Height)
	fmt.Println(block.Hash)
	fmt.Println(block.PrevBlockHash)
	fmt.Println("-----------------------------------------")

	return block
}

//2、单独写一个创建创世区块
func CreateGenesisBlock(data string) *Block {
	return NewBlock(data,1, []byte{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})
}

